package com.turman.glsample.base

import android.content.Context
import android.content.res.Resources
import android.opengl.GLES20
import android.util.Log
import androidx.annotation.RawRes
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

fun Context.readStringFromRaw(@RawRes resId: Int): String {
    return runCatching {
        val builder = StringBuilder()
        val reader = BufferedReader(InputStreamReader(resources.openRawResource(resId)))
        var nextLine: String? = reader.readLine()
        while (nextLine != null) {
            builder.append(nextLine).append("\n")
            nextLine = reader.readLine()
        }
        reader.close()
        builder.toString()
    }.onFailure {
        when(it) {
            is IOException -> {
                throw RuntimeException("Could not open resource: $resId", it)
            }
            is Resources.NotFoundException -> {
                throw RuntimeException("Resource not found: $resId", it)
            }
            else -> {}
        }
    }.getOrThrow()
}

fun loadShader(type: Int, shaderCode: String): Int {
    val shader = GLES20.glCreateShader(type)
    GLES20.glShaderSource(shader, shaderCode)
    GLES20.glCompileShader(shader)

    // Get the compilation status.
    val compileStatus = IntArray(1)
    GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compileStatus, 0)
    // If the compilation fails, delete the shader.
    if (compileStatus[0] == 0) {
        Log.e("loadShader", "Error compiling shader: " + GLES20.glGetShaderInfoLog(shader))
        GLES20.glDeleteShader(shader)
        throw RuntimeException("Shader compilation failed.")
    }
    return shader
}